package com.genius.util.DCS.Lock;

import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

public class RedisLock implements ILock {

    private String LockName;
    private StringRedisTemplate stringRedisTemplate;
    private final static String LOCK_SUFFIX = "lock:";
    public RedisLock(StringRedisTemplate stringRedisTemplate,String LockName){
        this.stringRedisTemplate = stringRedisTemplate;
        this.LockName = LockName;
    }

    @Override
    public boolean tryLock(long timeoutSec) {
        String key = LOCK_SUFFIX+LockName;
        Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(key, Thread.currentThread().toString(), timeoutSec, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(aBoolean);
    }

    @Override
    public void unLock() {
         stringRedisTemplate.delete( LOCK_SUFFIX+LockName);
    }
}
